<template>
  <el-dialog v-model="visible">
    <slot>
      <el-upload
        class="upload-demo"
        drag
        :action="uploadUrl"
        :on-success="handleSuccess"
        :on-error="handleError"
        :before-upload="beforeUpload"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip">
          只能上传<span style="color: red">.xls </span>或
          <span style="color: red">.xlsx </span>格式的文件
        </div>
      </el-upload>

      <!-- 下载模板按钮 -->
      <el-button type="success" @click="downloadTemplate"
        >下载导出模版</el-button
      >
    </slot>
  </el-dialog>
</template>

<script>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  props: {
    modelValue: Boolean,
    uploadUrl: {
      type: String,
      required: true
    },
    downloadUrl: {
      type: String,
      required: true
    }
  },
  emits: ['update:modelValue', 'uploaded'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)

    watch(
      () => props.modelValue,
      newVal => {
        visible.value = newVal
      }
    )

    watch(visible, newVal => {
      emit('update:modelValue', newVal)
    })

    const downloadTemplate = () => {
      window.location.href = props.downloadUrl
    }

    const handleSuccess = response => {
      if (response.success) {
        ElMessage.success(response.message)
      } else {
        ElMessage.error(response.message)
      }
      console.log('服务器响应:', response)
      // 导入成功回调
      emit('uploaded', response)
    }

    const handleError = () => {
      ElMessage.error('导入失败，请重试')
    }

    const beforeUpload = file => {
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        ElMessage.error('只能上传 Excel 文件!')
        return false
      }
      return true
    }

    return {
      visible,
      downloadTemplate,
      handleSuccess,
      handleError,
      beforeUpload
    }
  }
}
</script>

<style scoped>
/* 添加您需要的样式 */
</style>
